package com.insight.common.util.jsonschema;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class JsonschemaUtil {

	/**
	 * 生成JsonSchema
	 *
	 * @param descrip
	 * @param propertyList
	 * @return
	 */
	public static JSONObject getJsonSchema(JsonSchemaDescrip descrip, List<CommonProperty> propertyList) {
		JSONObject obj = new JSONObject();
		obj.put("$schema", descrip.get$schema());
		obj.put("type", descrip.getType());
		obj.put("title", descrip.getTitle());

		List<String> requiredArr = descrip.getRequired();
		obj.put("required", requiredArr);

		JSONObject properties = new JSONObject();
		putProperties(properties, propertyList);
		obj.put("properties", properties);

		return obj;
	}

	/**
	 * 生成JsonSchema 用于子对象
	 *
	 * @param title        子对象描述
	 * @param requiredArr  子对象必填属性名集合
	 * @param propertyList 子对象属性集合
	 * @return
	 */
	public static JSONObject getSubJsonSchema(String title, List<String> requiredArr, List<CommonProperty> propertyList) {
		JSONObject obj = new JSONObject();
		obj.put("type", "object");
		obj.put("view", "tab");
		obj.put("title", title);

		if (requiredArr == null) {
			requiredArr = new ArrayList<>();
		}
		obj.put("required", requiredArr);

		JSONObject properties = new JSONObject();
		putProperties(properties, propertyList);
		obj.put("properties", properties);

		return obj;
	}

	/**
	 * 将 CommonProperty 列表注入到 properties JSON 对象中
	 *
	 * @param properties   目标 JSON 对象
	 * @param propertyList CommonProperty 列表
	 */
	private static void putProperties(JSONObject properties, List<CommonProperty> propertyList) {
		if (propertyList == null) {
			log.error("propertyList is null");
			return;
		}
		for (CommonProperty commonProperty : propertyList) {
			Map<String, Object> map = commonProperty.getPropertyJson();
			if (map != null) {
				Object keyObj = map.get("key");
				Object propObj = map.get("prop");
				if (keyObj != null && propObj != null) {
					properties.put(keyObj.toString(), propObj);
				} else {
					log.warn("Property map missing 'key' or 'prop': {}", map);
				}
			} else {
				log.warn("commonProperty.getPropertyJson() returned null");
			}
		}
	}

}
